<template>
  <div class="main">
    <Header class="main_header"/>
    <div style="height: 63px;"></div>
    <div class="main_body">
      <div class="main_left">
        <a-button @click="handleSaveComments" class="main_left_tease_send_button" type="primary">
          发送
        </a-button>
        <div class="main_left_title">
          <Editor @sendContentToTease="receiveChildContent" @keyup="deleteSurplusImg"/>
        </div>
        <a-spin :spinning="spinning" :tip="'加载中'" :delay="300">
          <div class="main_left_content">
            <div v-for="(item,index) in commentsList" :key="item.id">
              <div class="main_left_content_for">
                <img :src="item.user.avatar" class="main_left_content_for_img" alt="头像">
                <div>
                  <div class="main_left_content_for_nickname">{{ item.user.nickname }}</div>
                  <div class="main_left_content_for_createTime">{{ item.createTime }}</div>
                  <div v-dompurify-html="item.content" class="main_left_content_for_content"></div>
                  <div class="main_left_content_for_operate">
                    <img @click="handleLike(item.id,index)" v-if="item.isLike===1" src="@/assets/img/answer/点赞.png"
                         class="main_left_content_for_operate_img" alt="点赞"/>
                    <img @click="handleLike(item.id,index)" v-else src="@/assets/img/answer/未点赞.png"
                         class="main_left_content_for_operate_img" alt="未点赞"/>
                    <div class="main_left_content_for_operate_count">{{ item.likeCount }}</div>
                    <a-button @click="showModalSecondComments(item)" class="main_left_content_for_operate_reply">回复
                    </a-button>
                  </div>
                  <div v-for="item2 in item.secondComments" :key="item2.id">
                    <div class="main_left_content_for_two">
                      <div v-if="item2.secondOneUserId===-1">
                        <div class="main_left_content_for_item">
                          <img :src="item2.secondTwoUser.avatar" class="main_left_content_for_two_img" alt="用户头像">
                          <div>
                            <div class="main_left_content_for_two_nickname">{{ item2.secondTwoUser.nickname }}</div>
                            <div class="main_left_content_for_two_createTime">{{ item2.createTime }}</div>
                            <div v-dompurify-html="item2.content" class="main_left_content_for_two_content"></div>
                            <a-button class="main_left_content_for_two_button" @click="showModalMuchComments(item2)">
                              回复
                            </a-button>
                          </div>
                        </div>
                      </div>
                      <div v-else>
                        <div class="main_left_content_for_item">
                          <img :src="item2.secondTwoUser.avatar" class="main_left_content_for_two_img" alt="用户头像">
                          <div>
                            <div class="main_left_content_for_two_nickname">{{ item2.secondTwoUser.nickname }}</div>
                            <div class="main_left_content_for_two_createTime">{{ item2.createTime }}</div>
                            <div v-dompurify-html="item2.content" class="main_left_content_for_two_content"></div>
                            <a-button class="main_left_content_for_two_button" @click="showModalMuchComments(item2)">
                              回复
                            </a-button>
                          </div>
                          <div class="main_left_content_for_two_reply">回复</div>
                          <img :src="item2.secondOneUser.avatar" class="main_left_content_for_two_img" alt="用户头像">
                          <div>
                            <div class="main_left_content_for_two_nickname">{{ item2.secondOneUser.nickname }}</div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-spin>
      </div>
      <div style="flex: 3;"></div>
      <div class="main_right">
        <About class="main_right_on"/>
        <Recommend class="main_right_under"/>
      </div>
    </div>

    <!-- 二级评论的对话框 -->
    <a-modal
        v-model:visible="visibleSecondComments"
        title="回复"
        :confirm-loading="confirmLoading"
        @ok="handleOkSecondComments"
        @cancel="handleCancelSecondComments"
        cancelText="取消"
        okText="确认"
    >
      <Editor @sendContentToTease="receiveChildContent"/>
    </a-modal>

    <!-- 多级评论的对话框 -->
    <a-modal
        v-model:visible="visibleMuchComments"
        title="回复"
        :confirm-loading="confirmLoading"
        @ok="handleOkMuchComments"
        @cancel="handleCancelMuchComments"
        cancelText="取消"
        okText="确认"
    >
      <Editor @sendContentToTease="receiveChildContent"/>
    </a-modal>
  </div>

</template>

<script setup lang="ts">
import Header from '@/components/header/index.vue'
import About from '@/views/home/tease/about/index.vue'
import Recommend from '@/views/home/tease/recommend/index.vue'
import Editor from '@/components/myRichText/teaseEditor/index.vue'
// @ts-ignore
import Publish from 'pubsub-js'
import {deleteImg} from "@/api/home/answer";
import {ref} from "vue";
import {
  getFirstAndSecondComments,
  getGiveALikeList,
  like,
  saveComments,
  saveSecondComments
} from "@/api/home/tease";
import {Comments, FirstAndSecondComments, GiveALike, SecondComments} from "@/model/home/tease";
// @ts-ignore
import cookie from 'js-cookie'
import {getText, isNull} from "@/utils/checkoutEditor";
import {message} from "ant-design-vue";
import {checkUserLogin} from "@/utils/getUser";

//是否显示加载中
const spinning = ref<boolean>(true);

//用户点赞列表
const giveALikeList = ref()

//点赞需要的参数
const giveALike = ref<GiveALike>({
  commentsId: 0,
  userId: 0
})

//判断当前用户是否点赞
const userIsGiveALike = () => {
  for (let i = 0; i < commentsList.value.length; i++) {
    for (let j = 0; j < giveALikeList.value.length; j++) {
      if (commentsList.value[i].id === giveALikeList.value[j].commentsId) {
        commentsList.value[i].isLike = giveALikeList.value[j].isLike
        break;
      } else {
        commentsList.value[i].isLike = 0
      }
    }
  }
}

//根据用户id查询用户点赞信息
const handleGiveALikeList = async () => {
  const res = await getGiveALikeList(giveALike.value.userId)
  giveALikeList.value = res.data.data.list
  setTimeout(async () => {
    //判断当前用户是否点赞
    await userIsGiveALike()
    spinning.value = false
  }, 1000)
}

//点赞
const handleLike = async (commentsId: number, index: number) => {
  giveALike.value.commentsId = commentsId
  if (!await checkUserLogin()) {
    message.warn('未登录，无法点赞')
  } else {
    like(giveALike.value).then(() => {
      commentsList.value[index].isLike = commentsList.value[index].isLike === 1 ? 0 : 1;
      //如果点赞，则点赞人数+1
      if (commentsList.value[index].isLike === 1) {
        message.success("点赞成功")
        commentsList.value[index].likeCount = commentsList.value[index].likeCount + 1
      } else {
        message.warn("取消点赞")
        commentsList.value[index].likeCount = commentsList.value[index].likeCount - 1
      }
    })
  }
}

//评论需要的参数
const comments = ref<Comments>({
  userId: 0,
  content: ''
})

//评论列表
const commentsList = ref<FirstAndSecondComments[]>([])

//获取一级和二级评论
const handleFirstAndSecondComments = () => {
  getFirstAndSecondComments().then((res) => {
    console.log(res.data.data.list)
    commentsList.value = res.data.data.list
    const regex = new RegExp('<img', 'gi')
    commentsList.value.map((item: any) => {
      item.content = item.content.replace(regex, `<img style="max-width: 100%; height: auto"`)
      item.secondComments.map((item2: any) => {
        item2.content = item2.content.replace(regex, `<img style="max-width: 100%; height: auto"`)
      })
    })
  })
}

//二级评论对话框
const visibleSecondComments = ref<boolean>(false);
//多级评论对话框
const visibleMuchComments = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);

//二级评论需要的参数
const secondComments = ref<SecondComments>({
  firstId: 0,
  secondOneUserId: -1,
  secondTwoUserId: 0,
  content: ''
})

//是否显示对话框(二级评论)
const showModalSecondComments = (row: any) => {
  if (cookie.get("userinfo") == null) {
    message.warn('未登录，无法回复')
    return;
  } else {
    visibleSecondComments.value = true;
    secondComments.value.firstId = row.id
    secondComments.value.secondOneUserId = -1
  }
};

//是否显示对话框(多级评论)
const showModalMuchComments = (row: any) => {
  if (cookie.get("userinfo") == null) {
    message.warn('未登录，无法回复')
    return;
  } else {
    visibleMuchComments.value = true;
    secondComments.value.firstId = row.firstId
    secondComments.value.secondOneUserId = row.secondTwoUserId
  }
};

//对话框点击确定回调(二级评论)
const handleOkSecondComments = () => {
  //校验消息是否为空
  let checkContent = getText(secondComments.value.content)
  if (isNull(checkContent)) {
    message.warn('内容不能为空！')
  } else if (secondComments.value.firstId === 0 || secondComments.value.secondTwoUserId === 0) {
    message.error('网络异常，请稍后重试！')
  } else {
    confirmLoading.value = true;
    setTimeout(() => {
      visibleSecondComments.value = false;
      confirmLoading.value = false;
      //清除富文本编辑器内容
      Publish.publish('clearContentToTease')
      //保存用户回复的消息
      saveSecondComments(secondComments.value).then((res) => {
        message.success(res.data.message)
        secondComments.value.content = '<p></p>'
        handleFirstAndSecondComments()
        handleGiveALikeList()
      })
      //删除多余图片
      deleteImg(imgDelName.value).then(() => {
      })
    }, 1000);
  }
}

//对话框点击确定回调(多级评论)
const handleOkMuchComments = () => {
  //校验消息是否为空
  let checkContent = getText(secondComments.value.content)
  if (isNull(checkContent)) {
    message.warn('内容不能为空！')
  } else if (secondComments.value.firstId === 0 || secondComments.value.secondTwoUserId === 0) {
    message.error('网络异常，请稍后重试！')
  } else {
    confirmLoading.value = true;
    setTimeout(() => {
      visibleMuchComments.value = false;
      confirmLoading.value = false;
      //清除富文本编辑器内容
      Publish.publish('clearContentToTease')
      //保存用户回复的消息
      saveSecondComments(secondComments.value).then((res) => {
        message.success(res.data.message)
        secondComments.value.content = '<p></p>'
        handleFirstAndSecondComments()
        handleGiveALikeList()
      })
    }, 1000)
  }
}

//对话框点击遮罩层或右上角叉或取消按钮的回调(多级评论)
const handleCancelMuchComments = () => {
  //删除多余图片
  deleteImg(imgDelName.value).then(() => {
  })
  //清除富文本编辑器内容
  Publish.publish('clearContentToTease')
  secondComments.value.content = '<p></p>'
}

//对话框点击遮罩层或右上角叉或取消按钮的回调(二级评论)
const handleCancelSecondComments = () => {
  //删除多余图片
  deleteImg(imgDelName.value).then(() => {
  })
  //清除富文本编辑器内容
  Publish.publish('clearContentToTease')
  secondComments.value.content = '<p></p>'
}

//用户发表评论
const handleSaveComments = () => {
  //校验消息是否为空
  let checkContent = getText(comments.value.content)
  if (isNull(checkContent)) {
    message.warn('内容不能为空！')
  } else {
    if (comments.value.userId == 0) {
      message.error('网络异常，请稍后重试！')
    } else {
      saveComments(comments.value).then((res) => {
        handleFirstAndSecondComments()
        message.success(res.data.message)
        //清除富文本编辑器内容
        Publish.publish('clearContentToTease')
        comments.value.content = '<p></p>'
      })
    }
  }
}

//删除的图片名数组,防止垃圾图片残留
const imgDelName = ref<any>([])

//接收子组件传过来的值
const receiveChildContent = (arr: string) => {
  comments.value.content = arr[0]
  secondComments.value.content = arr[0]
  imgDelName.value = arr[1]
}

//按删除键时并且多余的图片不为0时执行
const deleteSurplusImg = (e: any) => {
  if (e.keyCode === 8 && imgDelName.value.length != 0) {
    //删除多余图片
    deleteImg(imgDelName.value).then(() => {
    })
  }
}

//从cookie中获取用户id
const getUserId = () => {
  if (cookie.get('userinfo') != null) {
    comments.value.userId = JSON.parse(cookie.get('userinfo')).id
    giveALike.value.userId = JSON.parse(cookie.get('userinfo')).id
    secondComments.value.secondTwoUserId = JSON.parse(cookie.get('userinfo')).id
    if (comments.value.userId == 0) {
    } else {

    }
  } else {
    comments.value.userId = 0
    giveALike.value.userId = 0
    secondComments.value.secondTwoUserId = 0
  }
}

getUserId()
handleFirstAndSecondComments()
handleGiveALikeList()
</script>

<style lang="less" scoped>
.main {
  height: 100%;
  width: 100%;

  .main_header {
    height: 70px;
    position: fixed;
    width: 100%;
    z-index: 99999;
  }

  .main_body {
    display: flex;
    margin-left: 15%;
    margin-right: 15%;
    word-break: break-all;

    .main_left {
      margin-top: 1%;
      flex: 7;
      width: 70%;

      .main_left_tease_send_button {
        position: absolute;
        margin-left: 80vh;
        margin-top: 22vh;
        z-index: 1;
      }

      .main_left_content {
        margin-top: 20px;
        background-color: #ffffff;
        margin-right: 20px;

        .main_left_content_for {
          display: flex;
          margin-bottom: 20px;
          margin-right: 20px;

          .main_left_content_for_img {
            width: 70px;
            height: 70px;
            border-radius: 50%;
          }

          .main_left_content_for_nickname {
            margin-top: 5px;
            font-weight: bold;
            margin-left: 5px;
          }

          .main_left_content_for_createTime {
            margin-top: 5px;
            margin-left: 5px;
          }

          .main_left_content_for_content {
            margin-top: 10px;
            margin-left: 5px;
            margin-right: 30px;
            object-fit: cover;
          }

          .main_left_content_for_operate {
            display: flex;
            padding-bottom: 10px;

            .main_left_content_for_operate_img {
              width: 30px;
              height: 30px;
            }

            .main_left_content_for_operate_count {
              margin-left: 5px;
              margin-top: 5px;
            }

            .main_left_content_for_operate_reply {
              margin-left: 15px;
              background-color: powderblue;
            }
          }

          .main_left_content_for_two {
            margin-top: 10px;

            .main_left_content_for_item {
              display: flex;

              .main_left_content_for_two_img {
                width: 70px;
                height: 70px;
                border-radius: 50%;
              }

              .main_left_content_for_two_nickname {
                margin-top: 5px;
                font-weight: bold;
                margin-left: 5px;
              }

              .main_left_content_for_two_createTime {
                margin-top: 5px;
                margin-left: 5px;
              }

              .main_left_content_for_two_content {
                margin-top: 10px;
                margin-left: 5px;
                margin-right: 20px;
                object-fit: cover;
              }

              .main_left_content_for_two_button {
                margin: 5px;
                background-color: powderblue;
              }

              .main_left_content_for_two_reply {
                margin-left: 10px;
                margin-right: 10px;
                margin-top: 20px;
              }
            }

          }
        }
      }
    }

    .main_right {
      margin-top: 6%;
      position: fixed;
      top: 10px;
      margin-left: 49%;
      width: 355px;
    }
  }
}
</style>